import React, { useState, useEffect } from 'react';
import { Tree, message, Modal } from 'antd';
import { AntTreeNodeCheckedEvent } from 'antd/lib/tree';
import { updateGroupModules, getGroupModules } from '../service';
// import { useBossUser } from '@/hooks/user';

import { TAuthItem, TAuthData } from '../data';

const { TreeNode } = Tree;

interface Props {
  /**
   * 用户组 ID
   */
  groupId: string;
  /**
   * 是否显示
   */
  visible: boolean;
  onCancel: () => void;
  onOk: () => void;
}

/**
 * 从树型结构中获取 uri 列表
 * @param tree
 */
function getModuleFromTree(tree: TAuthItem[]): string[] {
  let uris: string[] = [];
  tree.forEach((item) => {
    uris.push(item.uri);
    if (item.children) {
      uris = uris.concat(getModuleFromTree(item.children));
    }
  });
  return uris;
}

function loop(list: TAuthItem[]) {
  return list.map((item) => {
    if (item.children && item.children.length) {
      return (
        <TreeNode title={item.name} key={item.uri} dataRef={item}>
          {loop(item.children)}
        </TreeNode>
      );
    }
    return <TreeNode title={item.name} key={item.uri} dataRef={item} />;
  });
}

export default function AuthModal(props: Props) {
  const { groupId } = props;
  const [authModal, setAuthModal] = useState<TAuthData>({
    addList: [],
    allList: [],
  });
  // const user = useBossUser();

  const { addList, allList } = authModal;

  const loadData = async () => {
    const res = await getGroupModules(groupId);
    if (res.code === 0) {
      const { data } = res;

      setAuthModal({
        addList: data.addList,
        allList: data.allList,
      });
    }
  };

  useEffect(() => {
    if (groupId) {
      loadData();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [groupId]);

  const onCancel = () => {
    if (typeof props.onCancel === 'function') {
      props.onCancel();
    }
  };

  const onOk = () => {
    if (typeof props.onOk === 'function') {
      props.onOk();
    }
  };

  const handleCheck = (idList: any, e: AntTreeNodeCheckedEvent) => {
    const moduleSets = {};
    idList.checked.forEach((item: string) => {
      const keys = item.split('.');
      keys.forEach((_, index) => {
        const path = keys.slice(0, index + 1).join('.');
        moduleSets[path] = true;
      });
    });
    const currentKey = e.node.props.eventKey;
    if (currentKey) {
      // 判断当前节点的选中状态
      if (e.checked) {
        // 将当前节点所有子节点选中
        const allKeys = getModuleFromTree(allList);
        const selectedKeys = allKeys.filter((key) => key.startsWith(currentKey));
        selectedKeys.forEach((key) => {
          moduleSets[key] = true;
        });
      } else {
        // 将当前节点所有子节点取消勾选
        Object.keys(moduleSets).forEach((item) => {
          if (item.startsWith(currentKey)) {
            moduleSets[item] = false;
          }
        });
      }
    }
    setAuthModal({
      addList: Object.keys(moduleSets).filter((k) => moduleSets[k]),
      allList,
    });
  };

  const onUpdateAuth = async () => {
    const res = await updateGroupModules(groupId, { idList: addList });
    if (res.code === 0) {
      message.success('修改成功！');
      onOk();
    }
  };

  // const canSetModule = user.can('auth.group.modules.update');
  return (
    <Modal
      title="权限管理"
      visible={props.visible}
      onOk={() => {
        onUpdateAuth();
      }}
      onCancel={onCancel}
      okButtonProps={
        {
          // disabled: !canSetModule,
        }
      }
      // okText={canSetModule ? '确定' : '无权限'}
    >
      <div style={{ height: '400px', overflowY: 'auto' }}>
        {allList ? (
          <Tree
            // disabled={!canSetModule}
            checkable
            checkStrictly
            defaultExpandedKeys={addList}
            defaultCheckedKeys={addList}
            checkedKeys={addList}
            onCheck={handleCheck}
          >
            {loop(allList)}
          </Tree>
        ) : (
          ''
        )}
      </div>
    </Modal>
  );
}
